<?php

/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2016-11-23
 * Time: 下午 5:09
 */
defined('ByShopWWI') or exit('Access Invalid!');
class payControl extends mobileMemberControl
{
    private $payment_config;

    public function __construct(){
        parent::__construct();

        if($_POST['payment_code']) {
            $model_mb_payment = Model('mb_payment');
            $condition = array();
            $mb_payment_info = $model_mb_payment->getMbPaymentOpenInfo($condition);
            if(!$mb_payment_info) {
                Tpl::output('error_msg','支付方式未开启');
                Tpl::showpage('order_pay_fail');
                return;
            }
            $this->payment_config = $mb_payment_info['payment_config'];
        }
    }

    /**
     * 实物商品订单
     */
    public function real_orderOp(){
        @header("Content-type: text/html; charset=".CHARSET);
        $pay_sn = $_POST['pay_sn'];
        if(empty($_POST['payment_code'])){
        	 $pay_sn = $_POST['pay_sn'];
             $condition = array();
             $condition['pay_sn'] = $pay_sn;
             $order_info = Model('order')->getOrderInfo($condition);
            if($order_info['order_state']==0){//hzx 2017-2-13
                Tpl::output('error_msg','订单已过期，请重新提交订单');
                Tpl::showpage('order_pay_fail');
                return;
            }
             // $payment_list = Model('mb_payment')->getMbPaymentList();

             $pay_info['pay_amount'] = $order_info['order_amount'];
             $pay_info['member_available_pd'] = $this->member_info['available_predeposit'];
             $pay_info['member_available_rcb'] = $this->member_info['available_rc_balance'];
             
             $model_member = Model('member');
             $member_info = $model_member->getMemberInfoByID($this->member_info['member_id']);

             $pay_info['member_paypwd'] = true;
            //hzx 2017-2-14注释
//             if(empty($this->member_info['member_paypwd'])){
//                $pay_info['member_paypwd'] = false;
//             }

             $pay_info['pay_sn'] = $order_info['pay_sn'];
             $pay_info['payed_amount'] = $order_info['pd_amount'];

            if($pay_info['payed_amount']>'0.00'){
               $pay_info['pay_amount'] = $pay_info['pay_amount']-$pay_info['payed_amount'];
            }

           $pay_in["pay_info"]=$pay_info;
           // $pay_in["pay_info"]["payment_list"]=$payment_list;

            Tpl::output('pay_in',$pay_in);
        	Tpl::showpage('payment');
        }else{
        
        $payment_code = $_POST['payment_code'];

        if(!preg_match('/^\d{18}$/',$pay_sn)){
            Tpl::output('error_msg','参数错误');
            Tpl::showpage('order_pay_fail');
            return;
        }

        //取订单列表
        $logic_payment = Logic('payment');
        $order_pay_info = $logic_payment->getRealOrderInfo($pay_sn, $_SESSION['member_id']);

        if(!$order_pay_info['state']) {
            Tpl::output('error_msg',$order_pay_info['msg']);
            Tpl::showpage('order_pay_fail');
            return;
        }
        $order_list = $order_pay_info['data']['order_list'];
        $order_id = '';
        $order_state=$order_pay_info['data']['order_list'][0]['order_state'];//hzx 2017-2-16
        if($order_state==0){
            Tpl::output('error_msg','订单已过期，请重新提交订单');
            Tpl::showpage('order_pay_fail');
            return;
        }
        if (!empty($order_list)) {//new status
            foreach ($order_list as $order_info) {
                if($order_info['order_state'] == ORDER_STATE_PAY){
                    Tpl::output('error_msg','您的订单已经支付，请勿重复支付');
                    Tpl::showpage('order_pay_fail');
                    return;
                }else if ($order_info['order_state'] == ORDER_STATE_NEW) {
                    $order_id = $order_info['order_id'];
                }
            }
        }
        //站内余额支付
        $order_list = $this->_pd_pay($order_list,$_POST);

        //计算本次需要在线支付（分别是含站内支付、纯第三方支付接口支付）的订单总金额
        $pay_amount = 0;
        $api_pay_amount = 0;
        $pay_order_id_list = array();

        if (!empty($order_list)) {
            foreach ($order_list as $order_info) {//order status
                if ($order_info['order_state'] == ORDER_STATE_NEW) {
                    $api_pay_amount += $order_info['order_amount'] - $order_info['pd_amount'] - $order_info['rcb_amount'];
                    $pay_order_id_list[] = $order_info['order_id'];
                    $order_id = $order_info['order_id'];
                }
                $pay_amount += $order_info['order_amount'];
            }
        }
        if (empty($api_pay_amount)) {
            redirect('index.php?act=pay&op=pay_ok&order_id='.$order_id.'&pay_sn='.$order_pay_info['data']['pay_sn'].'&pay_amount='.ncPriceFormat($pay_amount));
        }

        $result = Model('order')->editOrder(array('api_pay_time'=>TIMESTAMP),array('order_id'=>array('in',$pay_order_id_list)));
        if(!$result) {
            Tpl::output('error_msg','更新订单信息发生错误，请重新支付');
            Tpl::showpage('order_pay_fail');
            return;
        }

        $result = $logic_payment->getmbPaymentInfo($payment_code);

        if(!$result['state']) {
            Tpl::output('error_msg',$result['msg']);
            Tpl::showpage('order_pay_fail');
            return;
        }
        $payment_info = $result['data'];

        $order_pay_info['data']['api_pay_amount'] = ncPriceFormat($api_pay_amount);

        //如果是开始支付尾款，则把支付单表重置了未支付状态，因为支付接口通知时需要判断这个状态
        if ($order_pay_info['data']['if_buyer_repay']) {
            $update = Model('order')->editOrderPay(array('api_pay_state'=>0),array('pay_id'=>$order_pay_info['data']['pay_id']));
            if (!$update) {
                Tpl::output('error_msg','订单支付失败');
                Tpl::showpage('order_pay_fail');
                return;
            }
            $order_pay_info['data']['api_pay_state'] = 0;
        }

        //转到第三方API支付
        $this->_api_pay($order_pay_info['data'], $payment_info);
        }
    }

    /**
     * 支付成功页面
     */
    public function pay_okOp() {
        $pay_sn = $_GET['pay_sn'];
        if (!preg_match('/^\d{18}$/',$pay_sn)){
            Tpl::output('error_msg','该订单不存在');
            Tpl::showpage('order_pay_fail');
            return;
        }

        //查询支付单信息
        $model_order= Model('order');
        $pay_info = $model_order->getOrderPayInfo(array('pay_sn'=>$pay_sn,'buyer_id'=>$_SESSION['member_id']));
        if(empty($pay_info)){
            Tpl::output('error_msg','该订单不存在');
            Tpl::showpage('order_pay_fail');
            return;
         }

        $condition = array();
        $condition['order_id'] = $_GET['order_id'];
        $condition['buyer_id'] = $_SESSION['member_id'];
        $order_info = $model_order->getOrderInfo($condition,array('order_goods','order_common','store'));

        Tpl::output('pay_amount',$_GET['pay_amount']);
        Tpl::output('order_info',$order_info);
        Tpl::output('buy_step','step4');
        Tpl::showpage('order_pay_success');
    }

    /**
     * 第三方在线支付接口
     *
     */
    private function _api_pay($order_pay_info, $payment_info) {
        $inc_file = BASE_PATH.DS.'api'.DS.'payment'.DS.$payment_info['payment_code'].DS.$payment_info['payment_code'].'.php';

        if(!is_file($inc_file)){
            exit('支付接口不存在');
        }
       // require($inc_file);
        $param = $this->payment_config;

        // wxpay_jsapi
        if ($payment_info['payment_code'] == 'wxpay_jsapi') {
            $param['orderSn'] = $order_pay_info['pay_sn'];
            $param['orderFee'] = (int) (100 * $order_pay_info['api_pay_amount']);
            $param['orderInfo'] = C('site_name') . '商品订单' . $order_pay_info['pay_sn'];

            $param['orderAttach'] = 'v';
            if($order_pay_info['order_type'] == 'real_order'){
                $param['orderAttach'] = 'r';
            }else if($order_pay_info['order_type'] == 'pd_order'){
                $param['orderAttach'] = 'p';
            }
            //$param['orderAttach'] = ($order_pay_info['order_type'] == 'real_order' ? 'r' : 'v');
            $api = new wxpay_jsapi();
            $api->setConfigs($param);
            try {
                echo $api->paymentHtml($this);
            } catch (Exception $ex) {
                if (C('debug')) {
                    header('Content-type: text/plain; charset=utf-8');
                    echo $ex, PHP_EOL;
                } else {
                    Tpl::output('msg', $ex->getMessage());
                    Tpl::showpage('payment_result');
                }
            }
            exit;
        }

        $param['order_sn'] = $order_pay_info['pay_sn'];
        $param['order_amount'] = $order_pay_info['api_pay_amount'];

        $param['order_type'] = 'v';
        if($order_pay_info['order_type'] == 'real_order'){
            $param['order_type'] = 'r';
        }else if($order_pay_info['order_type'] == 'pd_order'){
            $param['order_type'] = 'p';
        }
       // $param['order_type'] = ($order_pay_info['order_type'] == 'real_order' ? 'r' : 'v');

        $payment_api = new $payment_info['payment_code'];
        $return = $payment_api->submit($param);
        echo $return;
        exit;
    }

    /**
     * 站内余额支付(充值卡、预存款支付) 实物订单
     */
    private function _pd_pay($order_list, $post) {
        if (empty($post['password'])) {
            return $order_list;
        }
        $model_member = Model('member');
        $buyer_info = $model_member->getMemberInfoByID($_SESSION['member_id']);
        if ($buyer_info['member_paypwd'] == '' || $buyer_info['member_paypwd'] != md5($post['password'])) {
            return $order_list;
        }

        if ($buyer_info['available_rc_balance'] == 0) {
            $post['rcb_pay'] = null;
        }
        if ($buyer_info['available_predeposit'] == 0) {
            $post['pd_pay'] = null;
        }
        if (floatval($order_list[0]['rcb_amount']) > 0 || floatval($order_list[0]['pd_amount']) > 0) {
            return $order_list;
        }

        try {
            $model_member->beginTransaction();
            $logic_buy_1 = Logic('buy_1');
            //使用充值卡支付
            if (!empty($post['rcb_pay'])) {
                $order_list = $logic_buy_1->rcbPay($order_list, $post, $buyer_info);
            }

            //使用预存款支付
            if (!empty($post['pd_pay'])) {
                $order_list = $logic_buy_1->pdPay($order_list, $post, $buyer_info);
            }

            //特殊订单站内支付处理
            $logic_buy_1->extendInPay($order_list);

            $model_member->commit();
        } catch (Exception $e) {
            $model_member->rollback();
            showMessage($e->getMessage(), '', 'html', 'error');
        }

        return $order_list;
    }

    /**
     * AJAX验证支付密码
     */
    public function check_pd_pwdOp(){
//   hyy     if (empty($_GET['password'])) exit('0');
        $buyer_info = Model('member')->getMemberInfoByID($_SESSION['member_id'],'member_paypwd');


        if($buyer_info['member_paypwd'] = ''){
            echo '3';
        }elseif ($buyer_info['member_paypwd'] === md5($_GET['password'])){
            echo '1';
        }else{
            echo '0';
        }


    }


    /**
     * 预存款充值
     */
    public function pd_orderOp(){
        $pdr_amount = abs(floatval($_POST['pdr_amount']));
        if ($pdr_amount <= 0) {
            Tpl::output('error_msg','请添加充值金额为大于或者等于0.01的数字');
            Tpl::showpage('order_pay_fail');
            return;
        }
        $model_pdr = Model('predeposit');
        $data = array();
        $data['pdr_sn'] = $pay_sn = $model_pdr->makeSn();
        $data['pdr_member_id'] = $_SESSION['member_id'];
        $data['pdr_member_name'] = $_SESSION['member_name'];
        $data['pdr_amount'] = $pdr_amount;
        $data['pdr_add_time'] = TIMESTAMP;
        $insert = $model_pdr->addPdRecharge($data);

        if ($insert) {
            $pdr_sn = $pay_sn;
            $payment_code = $_POST['payment_code'];
            $url = urlMember('predeposit');

            $logic_payment = Logic('payment');
            $result = $logic_payment->getmbPaymentInfo($payment_code);
            if (!$result['state']) {
                Tpl::output('error_msg',$result['msg']);
                Tpl::showpage('order_pay_fail');
                return;
            }
            $payment_info = $result['data'];

            $result = $logic_payment->getPdOrderInfo($pdr_sn, $_SESSION['member_id']);
            if (!$result['state']) {
                Tpl::output('error_msg',$result['msg']);
                Tpl::showpage('order_pay_fail');
                return;
            }
            if ($result['data']['pdr_payment_state'] || empty($result['data']['api_pay_amount'])) {
                Tpl::output('error_msg','该充值单不需要支付');
                Tpl::showpage('order_pay_fail');
                return;
            }
            //转到第三方API支付
            $this->_api_pay($result['data'], $payment_info);
        }
    }
}